package com.yiwei.jmx.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.jmx.R;
import com.yiwei.jmx.adapter.BorrowUseAdapter;
import com.yiwei.jmx.adapter.GridViewAddImgesAdpter;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.UploadImageBean;
import com.yiwei.jmx.api.model.DealIndexDetailModel;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.event.BorrowUseEvent;
import com.yiwei.jmx.util.ImageUtil;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.view.NestedGridView;
import com.yiwei.jmx.view.V19FrameLayout;
import com.yiwei.jmx.view.uploadImage.UploadImgAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class BorrowUseActivity extends BaseActivity {

    @BindView(R.id.txt_title)
    TextView txtTitle;

    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.upload_gridview)
    NestedGridView uploadGridview;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.txt_borrow_desc)
    EditText txtBorrowDesc;
    private BorrowUseAdapter adapter;
    private Unbinder unbiner;
    private UploadImgAdapter uploadImgAdapter;
    private GridViewAddImgesAdpter gridViewAddImgesAdpter;
    private List<String> datas;
    private BorrowUseEvent submitBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_borrow_use);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        submitBean = new BorrowUseEvent();
        txtTitle.setText("怎么用");
        ArrayList<DealIndexDetailModel.DataBean.UseType> totalData = getIntent().getParcelableArrayListExtra("data");
        adapter = new BorrowUseAdapter(this);
        adapter.setOnChooseListener(new BorrowUseAdapter.OnChooseListener() {
            @Override
            public void onSuccess(String id, String name) {
                submitBean.use_typeid = id;
                submitBean.type_name = name;
            }
        });
        list.setNestedScrollingEnabled(false);
        list.setAdapter(adapter);
        adapter.update(totalData);

        datas = new ArrayList<>();
        gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, this);
        gridViewAddImgesAdpter.setMaxImages(7);
        uploadGridview.setAdapter(gridViewAddImgesAdpter);
        uploadGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (position == gridViewAddImgesAdpter.getCount() - 1 && position < 6 && !gridViewAddImgesAdpter.isLastUpload()) {
//                    ((SendEvaluateActivity) getActivity()).goToTakePhoto(fragmentPoi);
                    goToTakePhoto();
                }
            }
        });
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    getUploadImg(file);
                }
            }

            @Override
            public void callTake(File file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {

                }
            }
        }, 1);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (uploadImgAdapter != null) {
            uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void getUploadImg(Bitmap bitmap) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        UploadImageBean bean = new UploadImageBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(bitmap, 100);
        Api.api_service.uploadImg(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    savePath(result.getUrl());
                });
    }

    public void goToTakePhoto() {

        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (uploadImgAdapter == null) {
                    initUploadImgAdapter();
                }
                uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
            }

            @Override
            public void onReject() {

            }

        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    public void savePath(String path) {
        gridViewAddImgesAdpter.getDatas().add(path);
        gridViewAddImgesAdpter.notifyDataSetChanged();
//        ((SendEvaluateActivity) getActivity()).getSubmitData().get(fragmentPoi).photos = gridViewAddImgesAdpter.getDatas();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick(R.id.btn_submit)
    public void onViewClicked() {
        if (TextUtils.isEmpty(submitBean.use_typeid)) {
            ToastUtil.makeTipsText("请选择借款用途");
            return;
        }
        submitBean.use_desc = UI.toString(txtBorrowDesc);
        submitBean.use_photos = gridViewAddImgesAdpter.getDatas();
        EventBus.getDefault().post(submitBean);
        finish();
    }
}
